package com.bops.web.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.bops.biz.permission.GrantManager;
import com.bops.cache.UserCache;
import com.bops.cache.UserCache.UserCO;
import com.bops.dal.user.dataobject.RenyuaninfoDO;
import com.bops.dal.user.queryobject.UserQuery;
import com.bops.service.CommonServiceLocator;
import com.bops.service.UserService;
import com.bops.valve.webuser.BopsWebUser;
import com.yue.commons.seine.web.annotations.ControllerAction;
import com.yue.commons.seine.web.servlet.mvc.AbstractController;
import com.yue.commons.seine.web.servlet.result.Forward;
import com.yue.commons.seine.web.servlet.result.Redirect;
import com.yue.commons.seine.web.servlet.result.View;
import com.yue.commons.seine.web.servlet.result.WebResult;
import com.yue.commons.seine.web.servlet.result.mime.NormalWebResult;

public class UserController  extends AbstractController {
    
    private UserService userService = CommonServiceLocator.getUserService();
    /**
     * @param model
     * @return
     * @throws Exception
     */
    @ControllerAction
    public WebResult changePsw(Map<String, Object> model) throws Exception {
        return new View("/user/changePsw.htm");
    }

    /**
     * @param model
     * @return
     * @throws Exception
     */
    @ControllerAction
    public WebResult changePswForm(Map<String, Object> model, String oldPassword, String password1, String password2)
                                                                                                                     throws Exception {
        if (password1 == null || !password1.equals(password2)) {
            model.put("ERROR_MESSAGE", "两次密码输入不一致，请重新输入！");
            return new View("/user/changePsw.htm");
        }

        BopsWebUser bopsWebUser = BopsWebUser.getCurrentUser();
        if (bopsWebUser == null || bopsWebUser.getMemberId() == null) {
            model.put("ERROR_MESSAGE", "用户没有登录，请重新登录！");
            return new View("/user/changePsw.htm");
        }
        UserCO userCO = UserCache.getUserCO(bopsWebUser.getMemberId());
        if (userCO==null)
        {
            model.put("ERROR_MESSAGE", "没有取到用户信息，请重新登录！");
            return new View("/user/changePsw.htm");
        }
        RenyuaninfoDO renInfoDO = userService.findRenyuaninfo(userCO.getEngId());
        if (renInfoDO!=null)
        { 
            if (!oldPassword.equals(renInfoDO.getPassword()))
            {
                model.put("ERROR_MESSAGE", "旧密码输入错误！");
                return new View("/user/changePsw.htm");
            }
            else
            {
                RenyuaninfoDO tmpRenyuaninfoDO = new RenyuaninfoDO();
                tmpRenyuaninfoDO.setEngId(userCO.getEngId());
                tmpRenyuaninfoDO.setPassword(password1);
                userService.updateRenyuaninfo(tmpRenyuaninfoDO);
                model.put("MESSAGE", "密码修改成功！");
                model.put("SUCCESS_FLAG", "true");
                return new View("/user/changePsw.htm");
            }
        }
        model.put("ERROR_MESSAGE", "没有取到用户信息，请重新登录！");
        return new View("/user/changePsw.htm");
    }
    
    @ControllerAction
    public WebResult completeUser(Map<String, Object> model, String q) throws Exception {
        q = new String(q.getBytes("iso8859-1"),"utf-8");
        List<String> userList = UserCache.getUserAutoSuggest(q,10);
        StringBuilder sb = new StringBuilder();
        for (String u : userList) {
           sb.append(u).append("\n");
        }
        return new NormalWebResult(sb.toString());
    }

    @ControllerAction
    public WebResult loginOut(Map<String, Object> model,String username,String password,HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getSession().setAttribute("bopsUserId",null);
        return new View("/user/login.htm");
    }
    
    @ControllerAction
    public WebResult login(Map<String, Object> model) throws Exception {
        return new View("/user/login.htm");
    } 

    @ControllerAction
    public WebResult doLogin(Map<String, Object> model,String username,String password,HttpServletRequest request) throws Exception {
        RenyuaninfoDO renInfoDO = userService.findRenyuaninfo(username);
        password = (password==null)?"":password;
        if (renInfoDO!=null)
        { 
            if (password.equals(renInfoDO.getPassword()) )
            {
            	 request.getSession().setAttribute("bopsUserId", renInfoDO.getId());
            	if("T".equals(renInfoDO.getStatus())){
            		 
                  return new Forward("/user/main.htm");
            	}
                  
              
            }
        }
        model.put("username",username);
        model.put("errorMsg","用户名或密码不正确！");
        return new View("/user/login.htm");
    }
    
    private String getEncodeStr(String str)
    {
        if (str==null||str.length()==0)
        {
            return str;
        }
        try {
            String str2 = new String(str.getBytes("iso8859-1"),"utf-8");
            str2 = java.net.URLDecoder.decode(str2, "UTF-8"); 
            return str2;
      } catch (UnsupportedEncodingException e) {
      }
      return str;
    }
    
    @ControllerAction
    public WebResult main(Map<String, Object> model) {
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("BIRTHDAY","true");
        List<RenyuaninfoDO> birthdayList = userService.listWake(map);
        model.put("birthdayList", birthdayList);
        
        if (GrantManager.hasPermission("user_tixing_role"))
        {
            map.clear();
            map.put("START_WORK_DATE","true");
            List<RenyuaninfoDO> startWorkList = userService.listWake(map);
            model.put("startWorkList", startWorkList);
            
        }
        
        
       return  new View("/user/main.htm");
    }


    // ////////////////////////////////////
    // //////// USER ////////////////
    // ////////////////////////////////////
    @ControllerAction
    public WebResult editUser(Map<String, Object> model, String engID, String action) {
        engID = getEncodeStr(engID);
        RenyuaninfoDO  userDO = new RenyuaninfoDO();
        if ("edit".equals(action)||"view".equals(action)) {
            model.put("action",action);
            userDO = userService.findRenyuaninfo(engID);
            if (userDO == null)
            {
                model.put("errorStatus", "没有编号是"+engID+"的用户！");
                return null;
            }
        }
        else
        {
            model.put("action","add");
        }
        if (GrantManager.hasPermission("user_showPWD_role"))
        {
            model.put("showPassword", "true");
        }
        if (GrantManager.hasPermission("view_salary_role"))
        {
            model.put("view_gongzhi", "true");
        }
        model.put("userDO", userDO);
        return null;
    }

    
    
    @ControllerAction
    public WebResult editUserForm(Map<String, Object> model, RenyuaninfoDO editUser, String action) {
        String engID= editUser.getEngId();
        if(engID==null || engID.trim().length()==0)
        {
            model.put("errorStatus", "编号是空,请重新输入!");
            model.put("userDO",editUser);
            model.put("action",action);
            return new View("/user/editUser.htm");
        }
        if ("add".equals(action))
        {
            RenyuaninfoDO userDO = userService.findRenyuaninfo(editUser.getEngId());
            if (userDO != null)
            {
                model.put("errorStatus", "编号是"+engID+"的用户已经存在，请重新输入！");
                model.put("userDO",editUser);
                model.put("action",action);
                return new View("/user/editUser.htm");
            }
            editUser.setPassword(editUser.getEngId());
            userService.insertRenyuaninfo(editUser);
            model.put("actionStatus", "添加成功!请继续添加用户!");
        }
        else
        {
            
            userService.updateRenyuaninfo(editUser);
            model.put("userDO", editUser);
            model.put("actionStatus", "修改成功!");
        }
        if (GrantManager.hasPermission("view_salary_role"))
        {
            model.put("view_gongzhi", "true");
        }
        return new View("/user/editUser.htm?action="+action+"&engID="+engID);
    }
    
    @ControllerAction
    public WebResult deleteUser(Map<String, Object> model, String engID) {
        engID = getEncodeStr(engID);
        if (engID!=null && engID.trim().length()>0) {
            userService.deleteByEngId(engID);
             model.put("actionStatus", engID+"已经被删除成功!");
        }
        return returnToUser(model);
    }
    
    @ControllerAction
    public WebResult searchUser(Map<String, Object> model,String showgongzhi) {
        model.put("notShowRecord", true);
        return null;
    }
    
    @ControllerAction
    public WebResult searchUserForm(Map<String, Object> model, UserQuery queryUser,String showgongzhi) {
        return returnToUser(model,queryUser,showgongzhi);
    }


    private WebResult returnToUser(Map<String, Object> model) {
        return returnToUser(model, null,"false");
    }

    private WebResult returnToUser(Map<String, Object> model, UserQuery queryUser,String showgongzhi) {
        if (queryUser == null) {
            queryUser = new UserQuery();
            queryUser.setNowPageIndex(0);
        }
        List<RenyuaninfoDO> userList = userService.listRenyuaninfo(queryUser);
        model.put("userDO", queryUser);
        if (userList!=null && userList.size()>0)
        {
            model.put("userList", userList);
        }
        model.put("pagniation", userList);
        model.put("showgongzhi", showgongzhi);
        if ("true".equals(showgongzhi) && GrantManager.hasPermission("view_salary_role"))
        {
            model.put("view_gongzhi", "true");
        }
        if (GrantManager.hasPermission("user_add_role"))
        {
            model.put("edit_renyuan_powder", "true");
        }
        return new View("/user/searchUser.htm");
    }
    
    
    

    
    

    
    /**
     * 把String转换为字符（如果异常就返回－1）
     * 
     * @param id
     * @return
     */
    public Integer convertInteger(String id) {
        try {
            return Integer.valueOf(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    
    
    private final String[] YEAR = {"2012","2013","2014","2015","2016","2017","2018","2019","2020"};
    private final String[] MONTH = {"1","2","3","4","5","6","7","8","9","10","11","12"};
}
